package com.zlc.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlc.common.utils.PageUtils;
import com.zlc.common.utils.Query;

import com.zlc.gulimall.product.dao.SpuImagesDao;
import com.zlc.gulimall.product.entity.SpuImagesEntity;
import com.zlc.gulimall.product.service.SpuImagesService;


@Service("spuImagesService")
public class SpuImagesServiceImpl extends ServiceImpl<SpuImagesDao, SpuImagesEntity> implements SpuImagesService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuImagesEntity> page = this.page(
                new Query<SpuImagesEntity>().getPage(params),
                new QueryWrapper<SpuImagesEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveImages(List<String> spuImages,Long spuId) {
        if(spuImages == null || spuImages.size() == 0){
            return ;
        }

        List<SpuImagesEntity> list = spuImages.stream().map((url) -> {
            SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
            //设置spuId
            spuImagesEntity.setSpuId(spuId);
            //设置name
            String fileName = this.getNameByImagesURL(url);
            spuImagesEntity.setImgName(fileName);
            //设置url
            spuImagesEntity.setImgUrl(url);
            //设置是否默认图
            spuImagesEntity.setDefaultImg(0);
            return spuImagesEntity;
        }).collect(Collectors.toList());

        this.saveBatch(list);
    }

    private String getNameByImagesURL(String url){
//        "http://ods地址/目录//UUID_filename.jpg"
        String[] s = url.split("_");
        return s[1];
    }

}